package com.test.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

public class TCPEchoServer {
	private static final int BUFSIZE = 32; // size of receive buff

	public static void main(String[] args) throws IOException {
		String[] argStrings = { "8086" };
		int serPort = Integer.parseInt(argStrings[0]);
		// create a server socket to accept client connection requests

		// A server socket waits for requests to come in over the network. It
		// performs some operation based on that request, and then possibly
		// returns a result to the requester.
		ServerSocket servSock = new ServerSocket(serPort);

		int recvMsgSize; // size of received message
		byte[] receiveBuf = new byte[BUFSIZE];// receive buffer

		while (true) {// run forever,accepting and servicing connections
			Socket clntSock = servSock.accept(); // get client connection
			SocketAddress clientAddress = clntSock.getRemoteSocketAddress();
			System.out.println("Handling client at " + clientAddress);

			InputStream in = clntSock.getInputStream();
			OutputStream out = clntSock.getOutputStream();

			// receive until client closes connection indicated by -1 return
			// Reads some number of bytes from the input stream and stores them
			// into the buffer array
			while ((recvMsgSize = in.read(receiveBuf)) != -1) {
				out.write(receiveBuf, 0, recvMsgSize);
			}
			clntSock.close(); // close the socket we are done with this client

		}
	}

}
